package com.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.apache.log4j.Logger;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.jsf.FacesContextUtils;

import com.builder.EnvaseBuilder;
import com.dao.BaseModelDAO;
import com.model.Envase;
import com.query.EnvaseQuery;
import com.util.JSFUtil;
import com.view.EnvaseView;

@ManagedBean
@ViewScoped
@SuppressWarnings("serial")
public class EnvaseController extends PaginableController<Envase> {

	private Logger log = Logger.getLogger(EnvaseController.class);
	private BaseModelDAO<Envase> dao;
	private Envase envase;
	private EnvaseQuery envaseQuery;

	@ManagedProperty("#{envaseView}")
	private EnvaseView envaseView;

	@ManagedProperty("#{envaseBuilder}")
	private EnvaseBuilder envaseBuilder;

	@SuppressWarnings("unchecked")
	public EnvaseController() {
		try {
			dao = (BaseModelDAO<Envase>) FacesContextUtils
					.getWebApplicationContext(FacesContext.getCurrentInstance())
					.getBean("envaseDAO");
			envaseQuery = new EnvaseQuery();
			addEdit = false;

		} catch (Throwable e) {
			log.error("Error al inicializar la clase EnvaseController", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}
	}


	public void query(ActionEvent event) {
		loadList();
	}

	public void edit(ActionEvent event) {
		try {
			envase = (Envase) lazyDM.getRowData();
			envase = dao.findFULL(envase.getID());
			envaseView = envaseBuilder.toView(envase);
			addEdit = true;
			
		} catch (Throwable e) {
			log.error("Error al editar", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}
	}

	public void delete(ActionEvent event) {
		try {
			envase = (Envase) lazyDM.getRowData();
			dao.delete(envase);
			loadList();
		} catch (Throwable e) {
			log.error("Error al eliminar", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}
	}

	public void add(ActionEvent event) {
		addEdit = true;
		clear();
	}

	public void save(ActionEvent event) {
		try {
			envase = envaseBuilder.toDomain(envaseView);

			if (envase.getID() != null) {
				dao.edit(envase);
				addEdit = false;
			} else {
				dao.save(envase);
			}
			clear();
			JSFUtil.saveMessage("Elemento guardado con exito",
					FacesMessage.SEVERITY_INFO);
			if (!addEdit) {
				loadList();
			}
		} catch (DataIntegrityViolationException e) {
			JSFUtil.saveMessage(
					"Error al guardar: La descripcion debe ser unica en el sistema.",
					FacesMessage.SEVERITY_ERROR);
		} catch (Throwable e) {
			log.error("Error al guardar", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}
	}

	public void cancel(ActionEvent event) {
		addEdit = false;
		lazyDM = null;
	}

	public void clear() {
		envase = new Envase();
		envaseView = new EnvaseView();
	}

	private void loadList() {

		lazyDM = new LazyDataModel<Envase>() {
			@Override
			public List<Envase> load(int first, int pageSize,
					String sortField, SortOrder sortOrder,
					Map<String, Object> filters) {

				Map<String, Object> filtro = new HashMap<String, Object>();
				filtro.put("descripcion", envaseQuery.getDescripcion());
				return dao.getList(first, pageSize, "descripcion", true, filtro,
						true);
			}
		};

		Map<String, Object> filtro = new HashMap<String, Object>();
		filtro.put("descripcion", envaseQuery.getDescripcion());
		lazyDM.setRowCount(dao.count(filtro, true).intValue());
	}


	public BaseModelDAO<Envase> getDao() {
		return dao;
	}


	public void setDao(BaseModelDAO<Envase> dao) {
		this.dao = dao;
	}


	public Envase getEnvase() {
		return envase;
	}


	public void setEnvase(Envase envase) {
		this.envase = envase;
	}


	public EnvaseQuery getEnvaseQuery() {
		return envaseQuery;
	}


	public void setEnvaseQuery(EnvaseQuery envaseQuery) {
		this.envaseQuery = envaseQuery;
	}


	public EnvaseView getEnvaseView() {
		return envaseView;
	}


	public void setEnvaseView(EnvaseView envaseView) {
		this.envaseView = envaseView;
	}


	public EnvaseBuilder getEnvaseBuilder() {
		return envaseBuilder;
	}


	public void setEnvaseBuilder(EnvaseBuilder envaseBuilder) {
		this.envaseBuilder = envaseBuilder;
	}


}
